//
//  Download.m
//  DownLoadDemo
//
//  Created by xalo on 16/6/17.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "Download.h"

@interface Download ()<NSURLSessionDownloadDelegate>

@property(nonatomic,strong)NSURLSession *session;
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;
//block用copy修饰
@property(nonatomic,copy)Downloading downloading; //正在下载
@property(nonatomic,copy)Complted complted;       //下载完成

@end

@implementation Download

- (NSURLSession *)session{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    }return _session;
}
//自定义  初始化的时候 创建一个下载任务
- (instancetype)initWithUrl:(NSURL *)url
{
    self = [super init];
    if (self) {
        //创建一个下载任务
        self.downloadTask = [self.session downloadTaskWithURL:url];
    }
    return self;
}
//开始下载
- (void)startDownload{
    [self.downloadTask resume];
}
//暂停下载
-(void)stopDownload{
    [self.downloadTask suspend];
}

//正在下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //下载百分比  已下载 /  总下载
    float nowDownload = totalBytesWritten / (float)totalBytesExpectedToWrite;
    NSLog(@"%.3g",nowDownload * 100);
    //如果block不为空 再去传至
    if (self.downloading) {
        self.downloading(bytesWritten,100 * nowDownload);
    }
}
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //我要们存放下载文件的路径
    NSString *filePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    //拼接文件的名字 , 名字从服务器上获取下来的
    NSString *fileName = downloadTask.response.suggestedFilename;
    //拼接后的路径
    NSString *newFilePath = [filePath stringByAppendingPathComponent:fileName];
    //文件管理器 , 把临时的文件移动到缓存文件夹下
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:newFilePath error:nil];
    NSLog(@"%@",newFilePath);
    if (self.complted) {
        self.complted(filePath,@"wangzhi");
    }
}
//下载时候和下载完成会走其中的block
-(void)downloading:(Downloading)downloading didFinished:(Complted)complted{
    //先走赋值  --- >  再走block属性赋值
    self.downloading = downloading;
    self.complted = complted;
}
@end
